<?php
declare(strict_types=1);

namespace TpAmisAdmin\Admin\controller;

use think\facade\View;
use think\facade\Session;
use think\facade\Db;
use think\Exception;
use think\admin\Time;
use TpAmisAdmin\Admin\common\utils\JwtAuth;
use TpAmisAdmin\Admin\model\Admin;

class Login extends Base
{
  /**
   * 登录页面
   * @return \think\response\Json
   */
  public function login()
  {
    $account = input('account');
    $password = input('password');
    if (!$account || !$password) {
      return $this->doError('请输入登录信息');
    }
    $user = Admin::where('account', $account)->where('password', md5($password))->findOrEmpty();
    if (!$user->isEmpty()) {
      if ($user->status <= 0) {
        return $this->doError('该账户被禁用');
      }
      $log = array();
      $dutime = Time::daysAgo(7);
      if ($user['token_time'] < $dutime) {
        $log['token'] = md5(time() . rand(1111, 99999999));
      } else {
        $log['token'] = $user['token'];
      }
      $log['last_time'] = $user['login_time'];
      $log['last_ip'] = $user['login_ip'];
      $log['logins'] = $user['logins'] + 1;
      $log['utime'] = time();
      $log['login_time'] = time();
      $log['token_time'] = time();
      $log['login_ip'] = $_SERVER["REMOTE_ADDR"];
      Admin::where('id', $user['id'])->update($log);
      // $user['token_time'] = $log['token_time'];
      // $user['token_time'] = Time::toDatetime($user['token_time'] + 604800);
      $user['token'] = JwtAuth::getInstance()->createToken($user['id'], 'admin', ['id' => $user['id'], 'account' => $user['account']]);
      return $this->doSuccess('登陆成功', ['token' => $user['token']]);
    }
    return $this->doError('登陆账户或密码错误');
  }
  public function logout()
  {
    return $this->doSuccess('ok');
  }
}
